package com.liuwa.framework.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.PropertySource;
import org.springframework.web.context.support.StandardServletEnvironment;

import java.util.*;

/**
 * 程序注解配置
 *
 * @author liuwa
 */
@Configuration
// 表示通过aop框架暴露该代理对象,AopContext能够访问
@EnableAspectJAutoProxy(exposeProxy = true)
// 指定要扫描的Mapper类的包的路径
@MapperScan({"com.liuwa.**.mapper", "com.liuwa.**.dao"})
public class ApplicationConfig
{

    @Autowired(required = false)
    public void initEnvironmentProperties(StandardServletEnvironment environment){
        if(environment == null){
            return;
        }
        Properties properties = new Properties();
        Iterator<PropertySource<?>> it = environment.getPropertySources().iterator();
        Set<String> propertyNames = new HashSet<String>();
        while (it.hasNext()){
            PropertySource ps = it.next();
            if(ps instanceof OriginTrackedMapPropertySource){
                propertyNames.addAll(Arrays.asList(((OriginTrackedMapPropertySource)ps).getPropertyNames()));
            }
        }
        for(String propertyName : propertyNames){
            if(propertyName.startsWith("spring.datasource")){
                continue;
            }
            properties.setProperty(propertyName,  environment.getProperty(propertyName));
        }


        EnvironmentProperties.setProperties(properties);
    }

    /**
     * 时区配置
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization()
    {
        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault());
    }
}
